function initializeReadingListPage(){
  if ( getCurrentPage("reading_list_items-index") && checkUserLoggedIn() ) {
    var publicSearchKey = '<%= ALGOLIASEARCH_PUBLIC_SEARCH_ONLY_KEY %>'
    client = algoliasearch('<%= ApplicationConfig["ALGOLIASEARCH_APPLICATION_ID"] %>', publicSearchKey);
    readinglistIndex = client.initIndex('ordered_articles_<%= Rails.env %>');
    commentsIndex = client.initIndex('ordered_comments_<%= Rails.env %>');
    var params = getQueryParams(document.location.search);
    document.getElementById('substories').dataset.tabs = '{"v": "'+(params.v || '')+'", "t": "'+(params.t || '')+'" }'
    postCommentFilter();
    getArticles("***onlytags***");
    document.getElementById("load-more-cta").onclick = function(event) {
      event.target.classList.remove("showing");
      getArticles("");
    }
  }
}



function getArticles(tag, num){
    var user = userData();
    var substoriesDiv = document.getElementById("substories");
    var algoliaIds = user.reading_list_ids.map(function(id){return "articles-"+id});
    var resultDivs = []
    var tags = {}
    readinglistIndex.getObjects(algoliaIds, function(err, content) {
      var results = num ? content.results.slice(0, num) : content.results ;
      results.forEach(function(story, i){
        if (story) {
          if (tag == "" || story.tag_list.indexOf(tag) > -1){
            resultDivs.push(buildArticleHTML(story));
          }
          story.tag_list.forEach(function(tag){
            if (tags[tag]){
              tags[tag] = tags[tag]+1;
            } else {
              tags[tag] = 1;
            }
          })
        }
      })
      if (tag != "***onlytags***") {
        substoriesDiv.innerHTML = resultDivs.join("");
        if ( resultDivs.length == 0) {
          var message = "<div style='text-align:left;margin-top:20px;'>This is where to find your bookmarked posts, but it looks like you have not bookmarked anything.</div>"
          substoriesDiv.innerHTML = message;
        }
      } else {
        if (results.lenth > 43) {
          document.getElementById("load-more-cta").classList.add("showing");
        }
        renderTags(tags);
      }
      initializeReadingListIcons();
    });
}

function getComments(){
  var user = userData();
  var algoliaIds = user.reading_list_ids.map(function(id){return "commentable_Article_"+id});
  var substories = document.getElementById("substories");
  var tabsObj = JSON.parse(substories.dataset.tabs);
  commentsIndex.search("*", {
      hitsPerPage: 45,
      attributesToHighlight: [],
      tagFilters: [algoliaIds,tabsObj["t"]],
  })
  .then(function searchDone(content) {
    var substoriesDiv = document.getElementById("substories");
    var resultDivs = []
    content.hits.forEach(function(comment){
      var aboveDiv = ""
        aboveDiv = aboveDiv + '<div class="comment-view-parent comment-view-commentable"><a href="'+comment.commentable.path+'">Re: '+comment.commentable.title+'</a></div>'
      if (comment.parent_path) {
        aboveDiv = aboveDiv + '<div class="comment-view-parent"><a href="'+comment.root_path+'">VIEW COMMENT TREE</a></div>'
      }
      resultDivs.push(aboveDiv+buildCommentHTML(comment));
    });
    substoriesDiv.innerHTML = '<div class="comment-trees"><h2>Recent Comment Activity</h2>'+resultDivs.join("<br/>")+'</div>';
    initializeCommentDropdown();
    initializeCommentsPage();
  });
}

function renderTags(tags){
  var sortedTags = [];
  for (var tag in tags) {
      sortedTags.push([tag, tags[tag]]);
  }
  sortedTags.sort(function(a, b) {
      return b[1] - a[1];
  });
  var tagDivs = []
  sortedTags.forEach(function(tag){
    var html = '<button class="query-filter-button query-tag-filter-button" data-tag="'+tag[0]+'">#'+tag[0]+' ('+tag[1]+')</button>'
    tagDivs.push(html)
  })
  document.getElementById("tag-filters").innerHTML = tagDivs.join("");
  var params = getQueryParams(document.location.search);
  var tag = filterXSS(params.t || "");
  tagFilters(tag);
}

function getQueryParams(qs) {
  qs = qs.split('+').join(' ');

  var params = {},
      tokens,
      re = /[?&]?([^=]+)=([^&]*)/g;

  while (tokens = re.exec(qs)) {
      params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
  }

  return params;
}

function tagFilters(tag){
  var substories = document.getElementById('substories');
  var filterButts = document.getElementsByClassName("query-tag-filter-button");
  for(var i = 0; i < filterButts.length; i++) {
    filterButts[i].classList.remove("selected");
    if (tag == filterButts[i].dataset.tag){
      filterButts[i].classList.add("selected");
    }
    filterButts[i].onclick = function(e){
      var tag = e.target.dataset.tag;
      window.scrollTo(0, 0);
      var className = e.target.className;
      var tabsObj = JSON.parse(substories.dataset.tabs);
      for(var i = 0; i < filterButts.length; i++) {
        filterButts[i].classList.remove("selected");
      }
      if (className.indexOf("selected") == -1 ) {
        e.target.classList.add("selected");
        assignTab(tabsObj, "t", tag)
        getStories();
      } else{
        assignTab(tabsObj, "t", "")
        getStories();
      }
    }
  }
}

function postCommentFilter(){
  var substories = document.getElementById('substories');
  var tabsObj = JSON.parse(substories.dataset.tabs);
  getStories()
  var filterButts = document.getElementsByClassName("query-type-filter-button");
  for(var i = 0; i < filterButts.length; i++) {
    filterButts[i].classList.remove("selected");
    if ((tabsObj["v"] || "posts") === filterButts[i].dataset.type){
      filterButts[i].classList.add("selected");
    }
    filterButts[i].onclick = function(e){
      for(var i = 0; i < filterButts.length; i++) {
        filterButts[i].classList.remove("selected");
      }
      var tabsObj = JSON.parse(substories.dataset.tabs);
      assignTab(tabsObj, "v", e.target.dataset.type);
      e.target.classList.add("selected");
      getStories()
    }
  }
}

function getStories(){
  var substories = document.getElementById('substories');
  var tabsObj = JSON.parse(substories.dataset.tabs);
  if (tabsObj["v"] == "comments") {
    getComments(tabsObj["t"] || "");
  } else {
    getArticles(tabsObj["t"] || "", 45);
  }
}

function assignTab(obj, tab, value) {
  obj[tab] = value
  substories.dataset.tabs = JSON.stringify(obj);
  window.history.replaceState(null, null, "/readinglist"+urlParams(obj));
  return obj
}

function urlParams(obj){
  if (obj["v"].length > 0 && obj["t"].length > 0) {
    return "?v="+obj["v"]+"&t="+obj["t"]
  } else if (obj["v"].length > 0) {
    return "?v="+obj["v"]
  } else if (obj["t"].length > 0) {
    return "?t="+obj["t"]
  } else {
    return ""
  }
}